<template>
  <div class="purchedit">
    <el-dialog
      title="编辑购货单"
      :visible.sync="dialogEdit"
      append-to-body
      width="75%">
      <div>
        <div class="bank-search mb-20 mr-15">
          <el-button size="medium" type="primary" @click="addRow">新增</el-button>
          <el-button size="medium" type="warning" @click="saveTable">保存</el-button>
        </div>
        <el-form :model="form" ref="form" size="medium" label-width="110px">
          <el-row :gutter="24" type="flex" justify="start">
            <el-col :span="6">
              <el-form-item label="供应商:" prop="supplier">
                <el-input v-model="form.supplier" clearable placeholder="供应商">
                  <el-button size="mini" slot="append" icon="el-icon-search" @click="open"></el-button>
                </el-input>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="单据日期:" prop="check_date">
                <el-date-picker
                  v-model="form.check_date"
                  type="date"
                  format="yyyy-MM-dd"
                  placeholder="单据日期"
                  style="width: 100%;">
                </el-date-picker></el-form-item></el-col>
            <el-col :span="6">
              <el-form-item label="单据编号:" prop="cg_no">
                <el-input v-model="form.cg_no" :disabled="true" placeholder="单据编号"></el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <div class="bank-form">
            <div class="form-item">
              <el-table
                :data="tableData.slice((currentPage-1)*pagesize,currentPage*pagesize)"
                class="table"
                stripe border
                show-summary
                :summary-method="getSummaries"
                @cell-click="editData"
                :row-class-name="tableRowClassName"
                :header-cell-style="{background:'#f3f3f3',textAlign: 'center'}"
                :cell-style="{ textAlign: 'center' }">
                <el-table-column type="index" width="50">
                </el-table-column>
                <el-table-column prop="goods" label="商品" width="160">
                  <template slot-scope="scope">
                    <span v-if="scope.row.index === tabClickIndex && tabClickLabel === '商品'">
                      <el-input v-model="scope.row.goods" size="mini" @blur="inputBlur">
                        <el-button slot="append" type="text"  icon="el-icon-search" @click="openGoods"></el-button>
                      </el-input>
                    </span>
                    <span v-else>{{ scope.row.goods }}</span>
                  </template>
                </el-table-column>
                <el-table-column prop="unit" label="单位" width="100">
                </el-table-column>
                <el-table-column prop="warehouse" label="仓库(批量)" width="100">
                  <template slot-scope="scope">
                    <span v-if="scope.row.index === tabClickIndex && tabClickLabel === '仓库(批量)'">
                      <el-input v-model="scope.row.warehouse" size="mini" @blur="inputBlur"/>
                    </span>
                    <span v-else>{{ scope.row.warehouse }}</span>
                  </template>
                </el-table-column>
                <el-table-column prop="amount" label="数量" width="100">
                  <template slot-scope="scope">
                    <span v-if="scope.row.index === tabClickIndex && tabClickLabel === '数量'">
                      <el-input v-model="scope.row.amount" size="mini" @blur="inputBlur"/>
                    </span>
                    <span v-else>{{ scope.row.amount }}</span>
                  </template>
                </el-table-column>
                <el-table-column prop="purchase_price" label="购货单价(元)" width="100">
                  <template slot-scope="scope">
                    <span v-if="scope.row.index === tabClickIndex && tabClickLabel === '购货单价(元)'">
                      <el-input v-model="scope.row.purchase_price" size="mini" @blur="inputBlur"/>
                    </span>
                    <span v-else>{{ scope.row.purchase_price }}</span>
                  </template>
                </el-table-column>
                <el-table-column prop="discount_rate" label="折扣率(%)" width="100">
                  <template slot-scope="scope">
                    <span v-if="scope.row.index === tabClickIndex && tabClickLabel === '折扣率(%)'">
                      <el-input v-model="scope.row.discount_rate" size="mini" @blur="inputBlur"/>
                    </span>
                    <span v-else>{{ scope.row.discount_rate }}</span>
                  </template>
                </el-table-column>
                <el-table-column prop="discount" label="折扣额" width="100">
                  <template slot-scope="scope">
                    <span v-if="scope.row.index === tabClickIndex && tabClickLabel === '折扣额'">
                      <el-input v-model="scope.row.discount" size="mini" @blur="inputBlur"/>
                    </span>
                    <span v-else>{{ scope.row.discount }}</span>
                  </template>
                </el-table-column>
                <el-table-column prop="purchase_amount" label="购货金额(元)" width="120">
                  <template slot-scope="scope">
                    <span v-if="scope.row.index === tabClickIndex && tabClickLabel === '购货金额(元)'">
                      <el-input v-model="scope.row.purchase_amount" size="mini" @blur="inputBlur"/>
                    </span>
                    <span v-else>{{ scope.row.purchase_amount }}</span>
                  </template>
                </el-table-column>
                <el-table-column prop="mileage" label="公里数" width="120">
                  <template slot-scope="scope">
                    <span v-if="scope.row.index === tabClickIndex && tabClickLabel === '公里数'">
                      <el-input v-model="scope.row.mileage" size="mini" @blur="inputBlur"/>
                    </span>
                    <span v-else>{{ scope.row.mileage }}</span>
                  </template>
                </el-table-column>
                <el-table-column prop="mile_price" label="每公里单价(元)" width="140">
                  <template slot-scope="scope">
                    <span v-if="scope.row.index === tabClickIndex && tabClickLabel === '每公里单价(元)'">
                      <el-input v-model="scope.row.mile_price" size="mini" @blur="inputBlur"/>
                    </span>
                    <span v-else>{{ scope.row.mile_price }}</span>
                  </template>
                </el-table-column>
                <el-table-column prop="note" label="备注" width="150">
                  <template slot-scope="scope">
                    <span v-if="scope.row.index === tabClickIndex && tabClickLabel === '备注'">
                      <el-input v-model="scope.row.note" size="mini" @blur="inputBlur"/>
                    </span>
                    <span v-else>{{ scope.row.note }}</span>
                  </template>
                </el-table-column>
                <el-table-column prop="source_no" label="源单号" width="200">
                </el-table-column>
                <el-table-column label="操作" width="220">
                  <template slot-scope="scope">
                    <!-- .native 表示监听组件根元素的原生事件。 -->
                    <el-button type="text" @click.native.prevent="deleteRow(scope.$index,tableData)">
                      <i class="el-icon-delete"></i>删除
                    </el-button>
                    <el-button type="text" @click="stockSearch(scope.$index,scope.row)">
                      <i class="el-icon-search"></i>商品库存查询
                    </el-button>
                  </template>
                </el-table-column>
              </el-table>
            </div>
            <!-- 分页-页码 -->
            <div class="page">
              <el-pagination
                @size-change="handleSizeChange"
                @current-change="handleCurrentChange"
                :current-page="currentPage"
                :page-sizes="[10, 20, 30, 40]"
                :page-size="pagesize"
                layout="total, sizes, prev, pager, next, jumper"
                :total="tableData.length">
              </el-pagination>
            </div>
          </div>
          <div class="mt-20">
            <el-form-item label="备注信息:" prop="fnote">
              <el-input type="textarea" v-model="form.fnote" clearable placeholder="暂无备注信息"></el-input>
            </el-form-item>
            <el-row :gutter="24" type="flex" justify="space-between">
              <el-col :span="6">
                <el-form-item label="优惠率:" prop="premium_rate"><span>
                  <el-input-number style="width: 176px;" :min="0" v-model="form.premium_rate" controls-position="right">
                  </el-input-number>%</span>
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="优惠金额:" prop="discount_amount">
                  <el-input v-model="form.discount_amount" clearable placeholder="优惠金额"></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="优惠后金额:" prop="after_amount">
                  <el-input v-model="form.after_amount" :disabled="true" placeholder="优惠后金额"></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="本次付款:" prop="payment">
                  <el-input v-model="form.payment" clearable placeholder="本次付款"></el-input>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row :gutter="24" type="flex" justify="space-between">
              <el-col :span="6">
                <el-form-item label="结算账户:" prop="settle_account">
                  <el-select v-model="form.settle_account" filterable clearable placeholder="结算账户" style="width: 100%;">
                    <el-option
                      v-for="item in accountList"
                      :key="item.value"
                      :label="item.label"
                      :value="item.value">
                    </el-option>
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="本次欠款:" prop="arrears">
                  <el-input v-model="form.arrears" :disabled="true" placeholder="本次欠款"></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="6"></el-col>
              <el-col :span="6"></el-col>
            </el-row>
          </div>
         </el-form>
      </div>

      <modal-supp ref="ModalSupp"></modal-supp>
      <modal-goods ref="ModalGoods"></modal-goods>
      <goods-stock ref="GoodsStock" :rows="stock_rows"></goods-stock>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogEdit = false">取 消</el-button>
        <el-button type="primary" @click="save">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
  import ModalSupp from '@/components/purchasing-system/ModalSupp';
  import ModalGoods from '@/components/purchasing-system/ModalGoods';
  import GoodsStock from '@/components/purchasing-system/GoodsStock';
  export default {
    components: {
      ModalSupp,
      ModalGoods,
      GoodsStock
    },
    name: 'PurchEdit',
    props:{
      rows:{}
    },
    data() {
      return {
        dialogEdit: false,
        stock_rows: '', //表格一行的数据
        tabClickIndex: null, // 点击的单元格
        tabClickLabel: '', // 当前点击的列名
        currentPage: 1, //当前页码
        pagesize: 10,    //每页的数据条数
        tableData: [], //表格数据
        form: {
          client: '',
          user: '',
          check_date: '',
          cg_no: 'CG202103161536361',
          contact: '',
          address: '',
          phone: '',
          order_type: 0,
          fnote: '',
          premium_rate: '0',
          discount_amount: '0',
          after_amount: '0.00',
          client_bear: '0.00',
          collect: '0.00',
          settle_account: '0',
          arrears: '100.00'
        },
        accountList: [
          {value: '0',label: '（空）'},
          {value: '1',label: '多账户'}
        ]
      }
    },
    //深度监听对象
    watch: {
      rows: {
        handler(newval, oldVal) {
          this.form = newval;
          this.tableData = [{
            goods: newval.goods,
            unit: newval.unit,
            warehouse: newval.warehouse,
            amount: newval.amount,
            purchase_price: newval.purchase_price,
            discount_rate: newval.discount_rate,
            discount: newval.discount,
            purchase_amount: newval.purchase_amount,
            mileage: newval.mileage,
            mile_price: newval.mile_price,
            note: newval.note,
            source_no: newval.source_no
          }]
        },
        deep: true
      }
    },
    created() {
    },
    methods:{
      //打开对话框
      openEdit() {
        this.dialogEdit = true;
      },
      // 确定
      save () {
        this.$refs['form'].validate(valid => {
          if (valid) {
            console.log('form',this.form)
            console.log('table',this.tableData)
            this.dialogEdit = false;
            this.$message.success('保存成功')
          } else {
            this.$message.error('表单验证失败!')
          }
        })
      },

      //供应商-对话框
      open() {
        this.$nextTick(()=>{
          this.$refs.ModalSupp.openSupp();
        });
      },
      //商品-选择-对话框
      openGoods() {
        this.$nextTick(()=>{
          this.$refs.ModalGoods.openGood();
        });
      },

      //商品库存查询
      stockSearch(index, row){
        this.stock_rows = row;
        this.$nextTick(()=>{
          this.$refs.GoodsStock.openStock();
        });
      },

      //添加一行
      addRow() {
        let j = {"goods": '',"unit": '',"warehouse": '',"amount": '',"purchase_price": '',"discount_rate": '',"discount": '',"purchase_amount": '',"mileage": '',"mile_price": '',"note": '',"source_no": ''}
        this.tableData.push(j);
        // this.tableData
      },
      //保存
      saveTable() {
        console.log('table', this.tableData)
        console.log('form',this.form)
      },

      //删除操作
      deleteRow(index, rows){
        rows.splice(index, 1);
      },

      tableRowClassName({row,rowIndex}) {
        // 把每一行的索引放进row
         row.index = rowIndex
      },

      // 添加明细原因 row 当前行 column 当前列
      //单元格被单击时
      editData(row, column, cell, event) {
        console.log(row,column)

        switch (column.label) {
          case '商品':
            this.tabClickIndex = row.index
            this.tabClickLabel = column.label
            break
          case '仓库(批量)':
            this.tabClickIndex = row.index
            this.tabClickLabel = column.label
            break
          case '数量':
            this.tabClickIndex = row.index
            this.tabClickLabel = column.label
            break
          case '购货单价(元)':
            this.tabClickIndex = row.index
            this.tabClickLabel = column.label
            break
          case '折扣率(%)':
            this.tabClickIndex = row.index
            this.tabClickLabel = column.label
            break
          case '折扣额':
            this.tabClickIndex = row.index
            this.tabClickLabel = column.label
            break
          case '购货金额(元)':
            this.tabClickIndex = row.index
            this.tabClickLabel = column.label
            break
          case '公里数':
            this.tabClickIndex = row.index
            this.tabClickLabel = column.label
            break
          case '每公里单价(元)':
            this.tabClickIndex = row.index
            this.tabClickLabel = column.label
            break
          case '备注':
            this.tabClickIndex = row.index
            this.tabClickLabel = column.label
            break
          default: return
        }
        console.log('商品', this.tabClickIndex, row, column, cell, event)
      },
      // 失去焦点初始化
      inputBlur(row, event, column) {
        this.tabClickIndex = null
        this.tabClickLabel = ''
      },

      //表格合计
      getSummaries(param) {
        const { columns, data } = param;
        const sums = []; //声明变量
        columns.forEach((column, index) => {
          if (index === 0) {
            sums[index] = '合计';
            return;
          }
          const values = data.map(item => Number(item[column.property]));
          if(
            column.property == "amount" || column.property == "discount" || column.property == "purchase_amount"
          ) {
            sums[index] = values.reduce((prev, curr) => {
              const value = Number(curr);
              if (!isNaN(value)) {
                return prev + curr;
              } else {
                return prev;
              }
            }, 0);
          } else {
          }
        });
        return sums;
      },

      //每页条数改变时触发事件,选择一页显示多少行
      handleSizeChange(val) {
        console.log(`每页 ${val} 条`);
        this.currentPage = 1;
        this.pagesize = val;
      },
      // 当前页改变时触发 跳转其他页
      handleCurrentChange(val) {
        console.log(`当前页: ${val}`);
        this.currentPage = val;
      }
    }
  }
</script>

<style>
</style>
